from PIL import Image
import os


name = 'esher.jpg'

im = Image.open(f"{name}")


N = 6 # разделить на N**2 

for i in range(N):
    for j in range(N):
        if i!=N and j!=N:
            im.crop(box=(im.size[0]/N*i, im.size[1]/N*j, im.size[0]/N*(i+1)-1, im.size[1]/N*(j+1)-1)).\
            save(f'img_parts/{name[:-4]}{str(i+1)}{str(j+1)}.jpg')


new_im = Image.new('RGB', (im.size[0], im.size[1]), (0,0,0)) # (255,165,0) = orange

img = [[0] * (N) for _ in range(N)]

for i in range(N):
    for j in range(N):
        img[i][j] = Image.open(f'img_parts/{name[:-4]}{str(i+1)}{str(j+1)}.jpg')
        # img[i][j].show()
        new_im.paste(img[i][j], (img[0][0].size[0]*i,img[0][0].size[1]*j))


# for i in range(N):
#     for j in range(N):
#         os.remove(f'img_parts/{name[:-4]}{str(i+1)}{str(j+1)}.jpg')
  
new_im.save(f'{name[:-4]}_merged.jpg', "JPEG") 
# new_im.show()